﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Windows.Forms;
using DigitalRune.Windows.TextEditor;

namespace Zove.Desktop {
    public class TextBoxWriter : TextWriter {

        private TextEditorControl textBox = null;

        private StringBuilder buff = null;

        public TextBoxWriter(TextEditorControl textbox) {
            this.textBox = textbox;
        }

        public override System.Text.Encoding Encoding {
            get { throw new NotImplementedException(); }
        }

        public override void Write(object value) {
            base.Write(value);
        }

        public override void Write(string value) {
            if (textBox.IsHandleCreated) {
                AppendText(value);
            } else {
                BufferText(value);
            }
        }

        public override void WriteLine(object value) {
            this.WriteLine(value.ToString());
        }

        public override void WriteLine(string value) {
            this.Write(value + Environment.NewLine);
        }

        public void AppendText(string value) {
            if (buff != null) {
                this.textBox.Text = this.textBox.Text + buff.ToString();
                buff = null;
            }

            this.textBox.Text = this.textBox.Text + value;
        }

        public void BufferText(string value) {
            if (buff == null) {
                buff = new StringBuilder();
            }

            buff.Append(value);
        }
    }
}
